package io.renren.modules.frt.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.frt.constant.DictConst;
import io.renren.modules.frt.entity.TaskEntity;
import io.renren.modules.frt.entity.TaskUserEntity;
import io.renren.modules.frt.entity.TemplateEntity;
import io.renren.modules.frt.service.TaskService;
import io.renren.modules.frt.service.TaskUserService;
import io.renren.modules.frt.service.TemplateService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;



/**
 * 创建任务
 *
 * @author qibing.huang
 * @email abingtech@163.com
 * @date 2018-11-18 23:36:42
 */
@RestController
@RequestMapping("frt/task")
public class TaskController extends AbstractController {
	private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TaskService taskService;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TaskUserService taskUserService;

    /**
     * 列表
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("/list")
    @RequiresPermissions("frt:task:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = taskService.queryPage(params);
        
        List<TaskEntity> list = (List<TaskEntity>)page.getList();
        if(list != null && list.size() > 0) {
        	for(TaskEntity task : list) {
        		TemplateEntity temp = templateService.selectById(task.getTempId());
        		if(temp != null) {
        			task.setTempName(temp.getName());
        		}
            }
        }

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("frt:task:info")
    public R info(@PathVariable("id") Long id){
        TaskEntity task = taskService.selectById(id);

        return R.ok().put("task", task);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("frt:task:save")
    public R save(@RequestBody TaskEntity task){
    	task.setCreateTime(new Date());
    	task.setSendStatus(DictConst.SEND_STATUS.UNSEND.getKey());//默认未下发
		taskService.insert(task);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("frt:task:update")
    public R update(@RequestBody TaskEntity task){
		taskService.updateById(task);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("frt:task:delete")
    public R delete(@RequestBody Long[] ids){
		taskService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
    
    /**
     * 下发
     */
    @RequestMapping("/send")
    @RequiresPermissions("frt:task:send")
    @Transactional
    public R send(@RequestBody Long[] ids){
    	SysUserEntity shiroUser = this.getUser();
    	//1、只有管理员并且任务是未下发状态才可以发起任务下发
    	if(io.renren.modules.sys.constant.DictConst.USER_LEVEL.ADMIN.getKey() == shiroUser.getLevel()) {
    		try {
				//2、任务下发到各省、市、县级用户，默认状态未上报，以及未审核通过的不能下发
				List<SysUserEntity> allUser = sysUserService.selectList(new EntityWrapper<SysUserEntity>().in("level", new Object[] {
						io.renren.modules.sys.constant.DictConst.USER_LEVEL.PROVINCE.getKey(),
						io.renren.modules.sys.constant.DictConst.USER_LEVEL.CITY.getKey(),
						io.renren.modules.sys.constant.DictConst.USER_LEVEL.COUNTRY.getKey()
				}).eq("check_status", 1));
				
				if(allUser == null || allUser.size() == 0) {
					return R.error("请先创建用户后再下发");
				}
				
				List<TaskUserEntity> taskUserList = new ArrayList<>();
				List<TaskEntity> taskList = new ArrayList<>();
				for(Long taskId : ids) {
					TaskEntity task = taskService.selectById(taskId);
					Assert.isNull(task, "任务id["+taskId+"]错误");
					for(SysUserEntity user : allUser) {
						TaskUserEntity taskUser = new TaskUserEntity();
						taskUser.setTaskId(taskId);
						taskUser.setUserId(user.getUserId());
						if(io.renren.modules.sys.constant.DictConst.USER_LEVEL.COUNTRY.getKey() == user.getLevel()) {//下发到县级用户，默认为未指派
							taskUser.setPointStatus(DictConst.POINT_STATUS.UNPOINT.getKey());
						}
						taskUser.setReportStatus(DictConst.REPORT_STATUS.UNREPORT.getKey());
						//填报完成度动态统计
						taskUserList.add(taskUser);
					}
					task.setSendStatus(DictConst.SEND_STATUS.SENDED.getKey());
					task.setSendTime(new Date());
					taskList.add(task);
					
					TaskUserEntity adminUser = new TaskUserEntity();//默认生成一笔，方便管理员查看已下发的任务，统一页面管理
					adminUser.setTaskId(taskId);
					adminUser.setUserId(shiroUser.getUserId());
					taskUserService.insert(adminUser);
				}
				
				taskUserService.insertBatch(taskUserList);
				
				//3、更新任务下发状态为已下发和下发时间
				taskService.updateBatchById(taskList);
			} catch (Exception e) {
				logger.error("任务下发失败", e);
				return R.error("任务下发失败");
			}
    	}
        return R.ok("任务下发成功");
    }
    
	/**
	 * 模板列表
	 */
	@GetMapping("/selectTemp")
	@RequiresPermissions("frt:task:selectTemp")
	public R selectTemp() {
		List<TemplateEntity> list = templateService.selectList(new EntityWrapper<TemplateEntity>());
		return R.ok().put("list", list);
	}
	
	/**
	 * 任务列表
	 */
	@GetMapping("/select")
	public R select(@RequestParam("tempId")String tempId) {
		List<TaskEntity> list = taskService.selectList(new EntityWrapper<TaskEntity>().eq("temp_id", tempId));
		return R.ok().put("list", list);
	}


}
